package public

import (
	"encoding/json"
	"gin/app/http/global"
	"gin/app/http/model/user"
	"gin/app/http/response"
	"gin/app/http/util"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"strconv"
	"time"
)

var secret = []byte("123456")

type UserInfo struct {
	UserName string `form:"user_name" binding:"required" json:"user_name"`
	PassWord string `form:"password" binding:"required" json:"password"`
}

func Login(c *gin.Context) {

	DecryptedData, _ := c.Get("DecryptedData")

	var userInfo UserInfo

	if err := json.Unmarshal([]byte(DecryptedData.(string)), &userInfo); err != nil {
		response.Fail(c, "用户不存在或密码不正确！", gin.H{
			"error": err.Error(),
		})
		return
	}
	//判断数据库是否存在该用户
	userData, bool := user.CheckUser(&user.UserModel{UserName: userInfo.UserName, Password: userInfo.PassWord})
	if !bool {
		response.Fail(c, "用户不存在或密码不正确！", gin.H{})
		return
	}
	data := util.User{
		UserId:   userData.UserId,
		UserName: userData.UserName,
	}
	signedString := util.EncryptToken(&data)

	//将token存入缓存
	prefix := viper.GetString("redis.prefix")
	user_id := strconv.Itoa(userData.UserId)
	Rdb := global.Rdb
	token, err := Rdb.Get(c, prefix+"_user_token_"+user_id).Result()
	if err == nil {
		Rdb.HDel(c, prefix+"_user_info"+user_id, token)
	}
	user_token, err := Rdb.HGet(c, prefix+"_user_token", user_id).Result()
	if err == nil {
		Rdb.HDel(c, prefix+"_user_info", user_token)
	}
	Rdb.Set(c, prefix+"_user_token_"+user_id, signedString, time.Hour*2)
	jsonData, _ := json.Marshal(userData)
	Rdb.HSet(c, prefix+"_user_info", signedString, jsonData)
	Rdb.HSet(c, prefix+"_user_token", user_id, signedString)
	response.Success(c, "请求成功！", gin.H{"token": signedString})

}
